package com.rtwo.videodownloader;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.Html;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.webkit.DownloadListener;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import junit.framework.Assert;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;

public class MainActivity extends Activity{

    private AutoCompleteTextView address;
    private TextView title;
    private ImageButton go,back,forward,refresh,bookmark,item;
    private WebView browser;
    private boolean videoCanLoad;
    private HashSet<String> videoUrl = new HashSet<String>();
    private DrawerLayout drawer;
    private LinearLayout mainPanel;
    private ListView menu;
    private SwipeRefreshLayout refreshLayout;
    private static final String BOOKMARKSICON = Environment.getExternalStorageDirectory()+"/videodownloader/pics/";

    //配置的初始化
    void initConfig(){
        title = (TextView)findViewById(R.id.title);
        address = (AutoCompleteTextView)findViewById(R.id.address);
        go = (ImageButton)findViewById(R.id.go);
        back = (ImageButton)findViewById(R.id.back);
        bookmark = (ImageButton)findViewById(R.id.bookmark);
        item = (ImageButton)findViewById(R.id.item);
        forward = (ImageButton)findViewById(R.id.forward);
        refresh = (ImageButton)findViewById(R.id.refresh);
        drawer = (DrawerLayout)findViewById(R.id.drawer);
        mainPanel = (LinearLayout)findViewById(R.id.main_panel);
        menu = (ListView)findViewById(R.id.menu);
        refreshLayout = (SwipeRefreshLayout)findViewById(R.id.refreshLayout);
        browserConfig();
        buttonConfig();
        textViewConfig();
        menuConfig();
        refreshLayoutConfig();
    }

    //按钮配置初始化
    void buttonConfig(){
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (browser.canGoBack()) {
                    new Common(back).scaleAnimate();
                    browser.goBack();
                    //使用前进后退的时候需要使用getOriginalUrl方法,而不能使用getUrl方法
                    //getOriginalUrl的解释是:the URL that was originally requested for the current page
                    address.setText(browser.getOriginalUrl());
                }
            }
        });
        forward.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (browser.canGoForward()) {
                    new Common(forward).scaleAnimate();
                    browser.goForward();
                    address.setText(browser.getOriginalUrl());
                }
            }
        });
        go.setOnClickListener(new View.OnClickListener() {
            String url = null;
            @Override
            public void onClick(View v) {
                new Common(MainActivity.this).storeHistoryData(address,"history_address");
                new Common(go).scaleAnimate();
                url = address.getText().toString();
                if (!url.startsWith("http://")) {
                    url = "http://" + url;
                }
                browser.loadUrl(url);
            }
        });
        address.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                new Common(MainActivity.this).storeHistoryData(address, "history_address");
                if (actionId == EditorInfo.IME_ACTION_GO) {
                    String url = address.getText().toString();
                    if (!url.startsWith("http://")) {
                        url = "http://" + url;
                    }
                    browser.loadUrl(url);
                }
                return true;
            }
        });
        refresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                browser.reload();
                new Common(refresh).scaleAnimate();
            }
        });
        item.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                drawer.openDrawer(Gravity.LEFT);
            }
        });
        bookmark.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Common(bookmark).scaleAnimate();
                AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
                dialog.setTitle("是否收藏该地址?");
                dialog.setCancelable(false);
                dialog.setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        new Common(MainActivity.this).storeData("bookmark_title", "bookmark_title", browser.getTitle());
                        boolean isStored = new Common(MainActivity.this).storeData("bookmark", "bookmark", address.getText().toString());
                        if (isStored) {
                            Toast.makeText(MainActivity.this, "收藏成功", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(MainActivity.this, "收藏失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
                dialog.setNegativeButton("否", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(MainActivity.this, "您取消收藏", Toast.LENGTH_SHORT).show();
                        dialog.dismiss();
                    }
                });
                dialog.show();
            }
        });
        drawer.setDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {

            }

            @Override
            public void onDrawerOpened(View drawerView) {
                item.setImageResource(R.drawable.item_open);
//                mainPanel.scrollBy(-menu.getWidth(),0);
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                item.setImageResource(R.drawable.item);
//                mainPanel.scrollBy(menu.getWidth(),0);
            }

            @Override
            public void onDrawerStateChanged(int newState) {

            }
        });
    }

    //title处理初始化
    void textViewConfig(){
        title.setTextColor(Color.BLUE);
        title.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(videoCanLoad){
                    HashSet<String> downloadFileList = (HashSet<String>) videoUrl.clone();
                    videoUrl.clear();
                    videoCanLoad = false;
                    title.setText("视频捕捉器");
                    title.setTextColor(Color.BLUE);
                    AlertDialog.Builder dialog = null;
                    for (String address : downloadFileList) {
                        dialog = new AlertDialog.Builder(MainActivity.this);
                        dialog.setTitle("是否开始下载?");
                        dialog.setMessage(Html.fromHtml("<Strong>对于商业视频网站来说开始检测到的一般都是视频广告</Strong>"));
                        dialog.setCancelable(false);
                        final String oAddress = address;
                        dialog.setPositiveButton("是", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                Random r = new Random(System.currentTimeMillis());
                                new DownloadFile(MainActivity.this, oAddress, r.nextInt() + ".mp4").goDownload();
                            }
                        });
                        dialog.setNegativeButton("否", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                        dialog.show();
                    }

                }
            }
        });
    }

    //浏览器配置初始化
    void browserConfig(){
        browser = (WebView)findViewById(R.id.browser);
        browser.setVerticalScrollbarOverlay(true); //指定的垂直滚动条有叠加样式
        browser.getSettings().setJavaScriptEnabled(true);//允许javascript执行
        browser.getSettings().setPluginState(WebSettings.PluginState.ON);//设置webview允许插件(因为需要播放视频,所有需要允许flash插件)
        browser.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);//允许javascript自动打开弹窗
        browser.getSettings().setAllowFileAccess(true);//设置允许文件接入
        browser.getSettings().setDefaultTextEncodingName("UTF-8");//设置编码
        browser.getSettings().setLoadWithOverviewMode(true);//webview内容适配屏幕宽度
        browser.getSettings().setUseWideViewPort(true);//设置webview支持viewport标签格式,比如手机网页的meta
        browser.setVisibility(View.VISIBLE);//设置可视(具体是什么可视,没有去查暂时~)
        browser.getSettings().setSupportZoom(true);//设置支持缩放
        browser.getSettings().setBuiltInZoomControls(true);//设置支持内置缩放控件
        //各种缓存配置
        browser.getSettings().setDomStorageEnabled(true);//如果有缓存 就使用缓存数据 如果没有 就从网络中获取
        browser.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        browser.getSettings().setDatabaseEnabled(true);
        browser.getSettings().setAppCacheEnabled(true);
        //把webview上的下载链接,转给第三方的工具,实现下载的功能
        browser.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                MainActivity.this.startActivity(intent);
            }
        });
        //设置网页的各种跳转,发生在webview上,而不是启用其他的浏览器
        browser.setWebViewClient(new WebViewClient() {
            //监听请求页面的地址,同时保证webview上的动作都是在该webview进行
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                browser.loadUrl(url);
                //这里需要使用getUrl,不能使用getOriginalUrl
                //getUrl的解释是:the URL for the current page
                address.setText(browser.getUrl());
                return true;
            }
            //监听请求页面的所有资源的地址
            @Override
            public void onLoadResource(WebView view, String url) {
                if (url.contains("mp4")&&!url.contains("{")&&!url.contains("}")){
                    MediaPlayer voice = MediaPlayer.create(MainActivity.this,R.raw.download_alert);
                    Log.v("address",url);
                    videoCanLoad = true;
                    title.setText("点击下载");
                    title.setTextColor(Color.RED);
                    videoUrl.add(url);
                    voice.start();
                }
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                if(refreshLayout.isRefreshing()){
                    refreshLayout.setRefreshing(false);
                    MediaPlayer.create(MainActivity.this,R.raw.refresh).start();
                }
            }


        });
        browser.setWebChromeClient(new WebChromeClient() {
            //响应js的alert事件
            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                return super.onJsAlert(view, url, message, result);
            }
        });
    }

    //listview菜单初始化
    void menuConfig(){
        SimpleAdapter simpleAdapter = new SimpleAdapter(this,getDrawerData(),R.layout.activity_drawer,new String[]{"icon_drawer","option_drawer"},new int[]{R.id.icon_drawer,R.id.option_drawer});
        menu.setAdapter(simpleAdapter);
        menu.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position){
                    case 0:
                        drawer.closeDrawer(Gravity.LEFT);
                        Intent intent = new Intent(MainActivity.this,BookmarkActivity.class);
                        MainActivity.this.startActivityForResult(intent, 1000);
                        break;
                    case 1:
                        drawer.closeDrawer(Gravity.LEFT);
                        Intent intent1 = new Intent(MainActivity.this,DownloadedVideoActivity.class);
                        MainActivity.this.startActivity(intent1);
                        break;
                    case 2:
                        drawer.closeDrawer(Gravity.LEFT);
                        AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
                        alert.setTitle("常见问题汇总");
                        alert.setMessage("1.如何下载视频?\n打开一个视频网站,点击播放,标题就会变成红色,点击就可以下载了;\n2.如何查看视频下载进度?\n" +
                                "下拉屏幕,在通知通知栏中就可以查看下载的视频了,包括暂停,继续等;\n3.如何查看已经下载的视频?\n点击左上角按钮,然后点击已下载" +
                                "视频,就可以查看相关视频,双击可以播放,也可以通过手指向左滑动进行播放和删除;\n4.为什么我下载的是广告?\n某些视频网站,比如优酷,都会有" +
                                "广告的播放,所以最先检测到的是广告,当检测到广告后,你点击下载,选择否就可以了,等你需要的视频播放的时候,再进行下载");
                        alert.show();
                        break;
                    default:
                        break;
                }
            }
        });
    }


    ArrayList<HashMap<String,Object>> getDrawerData(){
        ArrayList<HashMap<String,Object>> oDrawerData = new ArrayList<HashMap<String,Object>>();
        HashMap<String,Object> drawerData = null;
        String[] bookmarks = new String[]{"书签","已下载的视频","帮助"};
        int[] drawer_icon = new int[]{R.drawable.bookmark_drawer,R.drawable.download_drawer,R.drawable.question_drawer};
        for(int i=0;i<bookmarks.length;i++){
            drawerData = new HashMap<String,Object>();
            drawerData.put("icon_drawer",drawer_icon[i]);
            drawerData.put("option_drawer",bookmarks[i]);
            oDrawerData.add(drawerData);
        }
        return oDrawerData;
    }

    //refreshLayout初始化
    void refreshLayoutConfig(){
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                browser.loadUrl(browser.getUrl());
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initConfig();
        new Common(MainActivity.this).initAutoComplete("history_address", address);
        address.setText("http://www.haha.mx");
        browser.loadUrl("http://www.haha.mx");
        try {
            File file1 = new File(Environment.getExternalStorageDirectory()+"/videodownloader");
            File file2 = new File(Environment.getExternalStorageDirectory()+"/videodownloader/video");
            if(!file1.exists()){
                file1.mkdir();
            }
            if(!file2.exists()){
                file2.mkdir();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        Intent i_getvalue = getIntent();
        String action = i_getvalue.getAction();
        if (Intent.ACTION_VIEW.equals(action)) {
            String urlGot = i_getvalue.getDataString();
            address.setText(urlGot);
            browser.loadUrl(urlGot);
        }
    }

    @Override
    public void onBackPressed() {
        if(browser.canGoBack()){
            browser.goBack();
            address.setText(browser.getOriginalUrl());
        }
        else{
            AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
            dialog.setTitle("是否退出应用?");
            dialog.setCancelable(false);
            dialog.setPositiveButton("是", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    MainActivity.this.finish();
                }
            });
            dialog.setNegativeButton("否", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            dialog.show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch(requestCode){
            case 1000:
                if(resultCode==RESULT_OK){
                    Log.v("address",data.getDataString());
                    address.setText(data.getDataString());
                    browser.loadUrl(data.getDataString());
                }
        }
    }
}



